<?php

namespace App\Store\Models\Goods;

use App\Common\Services\Common;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsBrand;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsContent;
use App\Store\Models\Basic\GoodsCraft;
use App\Store\Models\Basic\GoodsPricetype;
use App\Store\Models\Basic\GoodsStone;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Models\Basic\Supply;
use Illuminate\Support\Facades\DB;

class GoodsStockList extends Model
{
    protected $table = 'site_goods_stock_list';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];
        /**
     *获取列表
     */
    public static function getList(Request $request)
    {

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['storeinfo','startstoreinfo','goods_category','supply','goods_style','goods_craft','goods_pricetype','goods_stone','paytype_info','goods_brand','goods_content'])->where(['cp_id' => $cp_id,'is_del'=>1])->orderBy('create_at', 'desc');
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if($store_ids){//权限控制
            if(is_array($store_ids)){//获取当前权限下的门店
                $query->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }
        $request_store_ids =$request->store_ids??[];
        if(!empty($request_store_ids)){
            $query->whereIn('store_id',$request_store_ids);
        }


        $ids=$request->ids;
        $ids=is_array($ids)?$ids:(is_array(json_decode($ids,true))?json_decode($ids,true):[]);
        if(count($ids)>0){
            $query->whereIn('id',$ids);
        }


        $store_id = intval($request->store_id);//下拉单选搜索
        if ($store_id>0) {
            $query->where('store_id', $store_id);
        }


        $supply_id = intval($request->supply_id);//下拉单选搜索
        if ($supply_id>0) {
            $query->where('supply_id', $supply_id);
        }
        $goods_category_id = $request->goods_category_id;//下拉单选搜索
        if (!empty($goods_category_id)) {
            if(is_array($goods_category_id)){
                $query->whereIn('goods_category_id', $goods_category_id);
            }else{
                $query->where('goods_category_id', $goods_category_id);
            }
        }

        $goods_category_ids=$request->goods_category_ids;
        $goods_category_ids=is_array($goods_category_ids)?$goods_category_ids:(is_array(json_decode($goods_category_ids,true))?json_decode($goods_category_ids,true):[]);
        if(count($goods_category_ids)>0){
            $query->whereIn('goods_category_id',$goods_category_ids);
        }


        $goods_pricetype_id = intval($request->goods_pricetype_id);//下拉单选搜索
        if ($goods_pricetype_id>0) {
            $query->where('goods_pricetype_id', $goods_pricetype_id);
        }

        $goods_brand_id = intval($request->goods_brand_id);//下拉单选搜索
        if ($goods_brand_id>0) {
            $query->where('goods_brand_id', $goods_brand_id);
        }
        $goods_style_id = $request->goods_style_id;//下拉单选搜索
        if (!empty($goods_style_id)) {
            if(is_array($goods_style_id)){
                $query->whereIn('goods_style_id', $goods_style_id);
            }else{
                $query->where('goods_style_id', $goods_style_id);
            }
        }

        $stockstatus = intval($request->stockstatus);//下拉单选搜索
        if ($stockstatus==1) {//在售
            $query->where('count','>', 0);
        }elseif($stockstatus==2){
            $query->where('count','<=', 0);
        }

        $is_stock = $request->is_stock??0;
        if($is_stock==2){
            // 过滤库存为0的
            $query->where('count','>', 0);
        }


        $goods_cabinetgroup_id=intval($request->goods_cabinetgroup_id);

        if($goods_cabinetgroup_id>0){
            $query->whereHas('goods_category', function ($query) use ($goods_cabinetgroup_id) {
                $query->where('goods_cabinetgroup_id', $goods_cabinetgroup_id);
            });
        }


        $weight= $request->weight;
        if($weight>0){
            $query->where(function ($q) use ($weight) {
                $q->where('piece_weight', $weight)->orWhere('netglod_weight', $weight);
            });
        }

        $label_price= is_numeric($request->label_price)?$request->label_price*100:-1;
        if($label_price>=0){
            $query->where('label_price',$label_price);
        }


        // $start_time = strtotime($request->start_time) > 0 ? strtotime($request->start_time) : intval($request->start_time);
        // $end_time = strtotime($request->end_time) > 0 ? strtotime($request->end_time) : intval($request->end_time);
        // if ($start_time > 0 && $end_time > $start_time) {
        //     $query->where('create_at', '>=', $start_time)->where('create_at', '<=', $end_time);
        // }


        $goods_sn_code=$request->goods_sn_code;

        if($goods_sn_code!=''){
            $query->where('goods_sn_code',$goods_sn_code);
        }
        $goods_sn_code_list=$request->goods_sn_code_list;
        $goods_sn_code_list=$goods_sn_code_list?(is_array($goods_sn_code_list)?$goods_sn_code_list:(explode(',',$goods_sn_code_list))):[];
        if(count($goods_sn_code_list)>0){
            $query->whereIn('goods_sn_code',$goods_sn_code_list);
        }




        $goods_name=$request->goods_name;
        if($goods_name!=''){
            $query->where('goods_name','like','%'.$goods_name.'%');
        }


        //库存时间
        $start_time = (!is_numeric($request->start_time) && strtotime($request->start_time) > 0) ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = (!is_numeric($request->end_time) && strtotime($request->end_time) > 0) ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $query->where('stockin_at', '>=', $start_time)->where('stockin_at', '<=', $end_time);
        }


        $isgetall = intval($request->isgetall) ?? 0;

        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    public function storeinfo(){
        return $this->hasOne(SiteStore::class, 'id', 'store_id')->select('id','store_name','store_file_path','tracing_url','qrcode_url','brand_url');
    }

    public function startstoreinfo(){
        return $this->hasOne(SiteStore::class, 'id', 'start_stockin_store_id')->select('id','store_name');
    }



    public function goods_category(){
        return $this->hasOne(GoodsCategory::class, 'id', 'goods_category_id')->select('id','category_name','is_gram','is_virtually','goods_cabinetgroup_id','is_sujin','price_discount','goods_metal_id');
    }

    public function supply(){
        return $this->hasOne(Supply::class, 'id', 'supply_id')->select('id','supply_name');
    }

    public function goods_style(){
        return $this->hasOne(GoodsStyle::class, 'id', 'goods_style_id')->select('id','style_name');
    }

    public function goods_craft(){
        return $this->hasOne(GoodsCraft::class, 'id', 'goods_craft_id')->select('id','craft_name');
    }
    public function goods_pricetype(){
        return $this->hasOne(GoodsPricetype::class, 'id', 'goods_pricetype_id')->select('id','pricetype_name');
    }
    public function goods_stone(){
        return $this->hasOne(GoodsStone::class, 'id', 'goods_stone_id')->select('id','stone_name');
    }
    public function paytype_info(){
        return $this->hasOne(PaytypeList::class, 'id', 'goods_stone_id')->select('id','paytype_name');
    }

    public function goods_brand(){
        return $this->hasOne(GoodsBrand::class, 'id', 'goods_brand_id')->select('id','brand_name');
    }

    public function goods_content(){
        return $this->hasOne(GoodsContent::class, 'id', 'goods_content_id')->select('id','content_name');
    }

    /**
     * 商品库龄分析表
     */
    public static function gettimelist(Request $request)
    {
        $store_ids = $request['store_ids'] ?? [];
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        $query = self::with(['storeinfo', 'goods_category', 'goods_style'])->where(['is_del' => 1, 'cp_id' => $cp_id])
            ->whereIn('store_id', $store_ids);

        //商品类别
        $goods_category_ids = $request['goods_category_ids'];
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);
        if (count($goods_category_ids) > 0) {
            $query->whereIn('goods_category_id', $goods_category_ids);
        }

        //款式
        $goods_style_id = $request['goods_style_id'] ?? 0;
        if ($goods_style_id > 0) {
            $query->where('goods_style_id', $goods_style_id);
        }

        $query->groupBy('store_id', 'goods_category_id', 'goods_style_id')
            ->select('store_id', 'goods_category_id', 'goods_style_id', DB::raw('sum(count) as count'));

        $isgetall = $request->isgetall ?? 0;
        if ($isgetall === 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        }

        $list = $query->get()->toArray();
        return ['list' => $list];
    }

    /**
     * 库龄时间短分析
     */
    public static function gettimetotal($item, $start_time, $end_time)
    {
        $one = GoodsStockList::where([
            'store_id' => $item['store_id'],
            'goods_category_id' => $item['goods_category_id'],
            'goods_style_id' => $item['goods_style_id'],
            'is_del'=>1
        ]);
        if ($start_time) {
            $one = $one->where('create_at', '>=', $start_time);
        }
        if ($end_time) {
            $one = $one->where('create_at', '<=', $end_time);
        }

        $one = $one->groupBy('goods_style_id')
            ->select('store_id', 'goods_category_id', 'goods_style_id', 'count', 'label_price', DB::raw('sum(count) as count,sum(count*label_price) as money'))
            ->first();
        if ($one) {
            return $one->toArray();
        }
        return [];
    }

    /**
     * 批量获取的库存商品
     * @param $cp_id
     * @param $goodsIds
     * @return mixed[]
     */
    public function getGoodsStockByIds($cp_id,$goodsIds)
    {
        $stock = GoodsStockList::query()
            ->where('cp_id',$cp_id)
            ->where('is_del',1)
            ->whereIn('id',$goodsIds)
            ->get()
            ->pluck(null,'id')
            ->toArray();

        if(!empty($stock)){
            $categoryIds= array_column($stock,'goods_category_id');
            $category=GoodsCategory::query()
                ->where('cp_id',$cp_id)
                ->where('is_del',1)
                ->whereIn('id',$categoryIds)
                ->get()
                ->pluck('is_gram','id')
                ->toArray();

            foreach ($stock as &$item){
                $item['is_gram'] =$category[$item['goods_category_id']]??0;
            }

        }

        return  $stock;

    }
}
